package cn.dai.wechat.config;

import com.alibaba.fastjson.JSONObject;
import cn.dai.util.HttpUtil;
import cn.dai.wechat.pojo.WechatTokenDto;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author daijiyong
 */
@Slf4j
public class WechatTokenConfig {

    public static final String WECHAT_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    private static final ConcurrentHashMap<String, WechatTokenDto> tokenMap = new ConcurrentHashMap<>();

    public static synchronized WechatTokenDto updateWechatToken(String corpId, String corpSecret) {
        WechatTokenDto wechatTokenDto = null;
        Map<String, String> params = new HashMap<>();
        params.put("corpid", corpId);
        params.put("corpsecret", corpSecret);
        try {
            String result = HttpUtil.doGet(WECHAT_TOKEN_URL, params);
            JSONObject json = JSONObject.parseObject(result);
            if ("0".equals(json.getString("errcode"))) {
                wechatTokenDto = WechatTokenDto.builder(json);
                tokenMap.put(corpId + corpSecret, wechatTokenDto);
                log.info("更新企业微信token成功：{}", result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新企业微信token失败：{}", e);
        }
        return wechatTokenDto;
    }

    public static synchronized Boolean expires(Long expires) {
        return System.currentTimeMillis() - expires >= 0;
    }

    public static WechatTokenDto getWechatToken(String corpId, String corpSecret) {
        WechatTokenDto wechatTokenDto = tokenMap.get(corpId + corpSecret);
        if (wechatTokenDto == null || expires(wechatTokenDto.getExpires())) {
            wechatTokenDto = updateWechatToken(corpId, corpSecret);
        }
        return wechatTokenDto;
    }

}
